<template>
	<div class="import-dialog-index">
		<div style="display: flex;align-items: center;">
			<div>请选择数据替换方式：</div>
			<el-radio-group v-model="radio" @change="handleRadioChange">
				<el-radio :label="1">尾部追加数据</el-radio>
				<el-radio :label="2">替换所有数据</el-radio>
			</el-radio-group>
		</div>
		<el-divider></el-divider>
		<el-button type="primary" size="medium" @click="go2Download">导入模板下载</el-button>
		<el-upload style="margin-top: 20px;" class="upload-demo" drag :action="baseUrl + action" :headers="headers" :show-file-list="false"
					:on-success="handleAvatarSuccess" :data="requestData" :before-upload="beforeAvatarUpload">
			<i class="el-icon-upload"></i>
			<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
			<div class="el-upload__tip" slot="tip">只能上传<b style="color: #f56c6c">{{ fileType.join("/") }}</b>文件，且不超过<b style="color: #f56c6c">{{ fileSize }}MB</b> </div>
		</el-upload>
	</div>
</template>

<script>
	import {
		getToken
	} from '@/utils/auth'

	export default {
		props: {
			action: {
				type: String,
				default: ""
			},
			// 大小限制(MB)
			fileSize: {
			  type: Number,
			  default: 2,
			},
			// 文件类型, 例如['png', 'jpg', 'jpeg']
			fileType: {
			  type: Array,
			  default: () => ["xls", "xlsx"],
			},
		},
		data() {
			return {
				radio: 1,
				baseUrl: process.env.VUE_APP_BASE_API,
				headers: {
					Authorization: getToken()
				},
				requestData: {}
			}
		},
		mounted() {
			this.requestData = {
				type: this.radio
			}
		},
		methods: {
			handleRadioChange(val){
				this.requestData = {
					type: val
				}
			},
			go2Download() {
				this.$emit("downloadTemplate")
			},
			handleAvatarSuccess(response, file, fileList) {
				this.$modal.closeLoading()
				if (response.code !== 200) {
					this.$message.error(response.msg || "导入失败")
				} else {
					this.$message.success("导入成功")
					this.$emit("close")
				}
			},
			beforeAvatarUpload(file) {
				// 校检文件类型
				if (this.fileType) {
				  const fileName = file.name.split('.');
				  const fileExt = fileName[fileName.length - 1];
				  const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
				  if (!isTypeOk) {
				    this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
				    return false;
				  }
				}
				// 校检文件大小
				if (this.fileSize) {
				  const isLt = file.size / 1024 / 1024 < this.fileSize;
				  if (!isLt) {
				    this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
				    return false;
				  }
				}
				this.$modal.loading("正在导入数据，请稍候...");
			},
		},
	}
</script>

<style lang="scss">
	.import-dialog-index {}
</style>